import { Button } from '@/components/ui/button';
import { Moon, Sun } from 'lucide-react';
import * as React from 'react';

export function ThemeToggle() {
  const [dark, setDark] = React.useState(false);

  React.useEffect(() => {
    const saved = localStorage.getItem('theme');
    if (saved === 'dark' || (!saved && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
      document.documentElement.classList.add('dark');
      setDark(true);
    } else {
      document.documentElement.classList.remove('dark');
      setDark(false);
    }
  }, []);

  const onToggle = () => {
    if (dark) {
      document.documentElement.classList.remove('dark');
      localStorage.setItem('theme', 'light');
      setDark(false);
    } else {
      document.documentElement.classList.add('dark');
      localStorage.setItem('theme', 'dark');
      setDark(true);
    }
  }

  return (
    <Button
      className='rounded ml-2 p-2 hover:bg-gray-200 dark:hover:bg-gray-700'
      title={dark ? '浅色' : '深色'}
      onClick={onToggle}
    >
      {dark ? <Sun size={18}/> : <Moon size={18} />}
    </Button>
  )
}